package  
{
  import flash.display.DisplayObjectContainer;
  import flash.events.Event;
  import flash.events.KeyboardEvent;
  import flash.geom.Point;
  import flash.sampler.NewObjectSample;
  import flash.ui.Keyboard;
  import mge.Timer;
	/**
   * ...
   * @author ivan
   */
  public class Scroller 
  {
    
    public function Scroller(parent:DisplayObjectContainer) 
    {
      this.parent = parent;
      
      parent.stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
      parent.stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
      parent.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }
    
    private function onKeyDown(e:KeyboardEvent):void
    {
      if (down) return;
      if (e.keyCode != Keyboard.UP &&
          e.keyCode != Keyboard.DOWN &&
          e.keyCode != Keyboard.RIGHT &&
          e.keyCode != Keyboard.LEFT)
      {
        return;
      }
      
      down = true;
      timer.start();
      if (e.keyCode == Keyboard.UP) direction = new Point(0, 5);
      if (e.keyCode == Keyboard.DOWN) direction = new Point(0, -5);
      if (e.keyCode == Keyboard.LEFT) direction = new Point(5, 0);
      if (e.keyCode == Keyboard.RIGHT) direction = new Point(-5, 0);
    }
    
    private function onKeyUp(e:KeyboardEvent):void
    {
      down = false;
      timer.start();
    }
    
    private function onEnterFrame(e:Event):void
    {
      if (down)
      {
        parent.y += direction.y * timer.getDelta();
        parent.x += direction.x * timer.getDelta();
      }
      else
      {
        parent.y += direction.y * (1 - timer.getDelta());
        parent.x += direction.x * (1 - timer.getDelta());
      }
      
    }
    
    private var timer:Timer = new Timer(250);
    private var direction:Point = new Point();
    private var parent:DisplayObjectContainer;
    private var down:Boolean;
  }

}